Components.utils.import("resource://seoprofesional/seopdb.jsm");
Components.utils.import("resource://seoprofesional/fetchers.jsm");

function LOG(msg) {
  var consoleService = Components.classes["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService);
  consoleService.logStringMessage(msg);
}

function extract_uri(uri) {
	var p0 = uri.indexOf("uri=");
	if (-1==p0)	return "";
	return uri.substr(p0+4);
}

function do_plot(uri) {
	uri = extract_uri(uri);
	if (""==uri) {
		$("#chart").html("");
		return;
	}

	var datasets = [];	// datasets for flot.plot
	var origdata = [];	// the values datasets were made from
	var ranks = [];	// the order of the ranks in datasets

	for (var ff = 0;ff<seop_global.fetchers.length;ff++) {
		var f = seop_global.fetchers[ff];
		if (f.enabled) {
			var tl = seopdb.get_tl(uri, f.id);
			if (tl.length>0) {
				var data = [];
				var od = [];
				var last = null;
				for (var i = 0;i<tl.length;i++) {
//					if (0)
					if (null!=last && last[1]!=tl[i][1]) {
						data.push(null);
						od.push(null);
					}
					//var d = tl[i][0];
					data.push([ tl[i][0].getTime(), tl[i][1]/f.max*100 ]);
					od.push(tl[i]);
					last = tl[i];
				}
				datasets.push({
					data: data,
/*					label: f.name,*/
					color: f.color
				});
				origdata.push(od);
				ranks.push(f);
			}
		}
	}

	$.plot($("#chart"), datasets, { 
		xaxis: { mode: "time", timeformat: seop_global.date_format },
		yaxis: { max: 100, tickFormatter: function (v, axis) { return v.toFixed(axis.tickDecimals) +"%" }},
		points: { show: true },
		lines: { show: true, fill: true },
		grid: { hoverable: true }/*,
		legend: { position: 'ne' }*/
	});
	function showTooltip(x, y, dt, val, rank) {
		var contents = format_date(dt, seop_global.date_format) + ":<br>" + rank.name + "=" + val;
		$('<div id="tooltip">' + contents + '</div>').css( {
			top: y + 5,
			left: x + 5,
		}).appendTo("body").fadeIn(200);
	}

	var previousPoint = null;
	$("#chart").bind("plothover", function (event, pos, item) {
//		$("#x").text(pos.x.toFixed(2));
//		$("#y").text(pos.y.toFixed(2));

		if (item) {
			if (previousPoint != item.datapoint) {
				previousPoint = item.datapoint;

				$("#tooltip").remove();
				var d = origdata[item.seriesIndex][item.dataIndex];
				showTooltip(item.pageX, item.pageY, d[0], d[1], ranks[item.seriesIndex]);
			}
		} else {
			$("#tooltip").remove();
			previousPoint = null;
		}
	});
}

